import bson
from flask import request, jsonify, g

from app.libs.error_code import Success
from app.libs.redprint import Redprint
from app.libs.run_cases import RunCases
from app.libs.tasks import execute_debug_task1
from app.libs.token_auth import login_required
from app.models.case_group import CaseGroupModel
from app.validates.case import UpdateCaseForm, DebugCaseForm
from app.validates.case_group import CaseGroupForm, AddCaseGroupForm, PutCaseGroupForm, CaseGroupPageForm
from app.libs.init import socket_io

api = Redprint('case_group')


@api.route('/<int:cid>', methods=['GET'])
@login_required
def get_case_group(cid):
    data = CaseGroupModel().get_page_group(cid)
    return Success(data=data)


@api.route('', methods=['POST'])
@login_required
def add_case_group():
    form = AddCaseGroupForm().validate_and_api()
    CaseGroupModel.add_group(form.name.data, g.user, form.id.data)
    return Success()


@api.route('/<int:g_id>', methods=['PUT'])
@login_required
def put_case_group(g_id):
    form = PutCaseGroupForm().validate_and_api()
    CaseGroupModel.put_group(g_id, form.name.data, form.trigger.data, form.execute_time.data)
    return Success()


@api.route('/<int:cid>', methods=['DELETE'])
@login_required
def delete_case_group(cid):
    CaseGroupModel().delete_case(cid)
    return Success()


@api.route('/debug', methods=['POST'])
@login_required
def debug_case_group():
    forms = request.json
    cases = []
    for form_data in forms:
        form = DebugCaseForm(re_data=form_data).validate_and_api()
        cases.append(form.data)
    task_id = CaseGroupModel.debug_case_group(cases)
    return Success(data=task_id)


@api.route('/debug/1', methods=['POST'])
@login_required
def debug_case_group2():
    forms = request.json
    cases = []
    for form_data in forms:
        form = DebugCaseForm(re_data=form_data).validate_and_api()
        cases.append(form.data)

    execute_debug_task1(cases, str(bson.ObjectId()))
    return Success()
